var select = '<select ' +
    'ng-model="current_col"' +
    'ng-change="add()"' +
    'ng-options="col as col.name for col in cols_copy">' +
    //'<option></option>' +
    '</select>';

var cols = '<div style="" ng-repeat = "order in orders">' +
    '<span class="sorter-span" style="" ng-click="order.toggle()">{{order.name}}' +
    '<i class="fa {{order.reverse? \'fa-sort-alpha-desc\':\'fa-sort-alpha-asc\'}}"></i>' +
    '</span>' +
    '<i class="fa fa-times" ng-click="order.remove()"></i>' +
    '</div>';

var option_nil = {
    name:'排序规则',
    id: undefined
};

module.exports = function () {
    return {
        restrict  : 'E',
        scope     : {
            sort: "=",
            cols: "="
        },
        template  : '<div class="sorter" ><!--label style="float: left;height: 30px;line-height: 30px;padding: 0 10px;">排序规则:</label-->'+ select + cols + '</div>',
        replace   : true,
        controller: ['$scope', '$element', function ($scope, $element) {
            $scope.cols_copy = $scope.cols.map(function(_){return _});

            $scope.cols_copy.unshift(option_nil);
            $scope.orders = [];
            $scope.current_col = option_nil;

            $scope.clear = function () {
                $scope.orders = [];
                $scope.sort = flat_orders();
            };

            $scope.add = function () {
                    var col = $scope.current_col;
                    if (!col.id) return;
                    if (-1 !== $scope.orders.findIndex(function (x) {
                            return x.id == col.id
                        }))return;
                    $scope.orders.push({
                        id     : col.id,
                        name   : col.name,
                        reverse: false,
                        toggle : function () {
                            this.reverse = !this.reverse;
                            $scope.sort = flat_orders();
                        },
                        remove : function () {
                            var to_remove = $scope.orders.indexOf(this);

                            $scope.orders.splice(to_remove, 1);
                            $scope.sort = flat_orders();
                            $scope.cols_copy.push(col);
                        }
                    });
                    $scope.cols_copy.splice($scope.cols_copy.indexOf(col), 1);
                    $scope.sort = flat_orders();
                    $scope.current_col = option_nil;
                };


            var flat_orders = function () {
                return $scope.orders.map(function (order) {
                    return order.reverse ? '-' + order.id : order.id
                });
            };

        }]
    }
};